﻿using System;
using ACompany.OrderProcessing.Infrastructure;
using ACompany.OrderProcessing.Infrastructure.CustomExceptions;
using NHibernate;

namespace ACompany.OrderProcessing.NHibernateRepository
{
    public class MHibernateUnitOfWork : IUnitOfWork
    {
        private readonly ISession _session;

        public MHibernateUnitOfWork()
        {
            _session = SessionFactory.GetCurrentSession();
        }

        public void Save(IAggregateRoot entity)
        {
            _session.SaveOrUpdate(entity);
        }

        public void Delete(IAggregateRoot entity)
        {
            _session.Delete(entity);
        }

        public void Commit()
        {
            using (var trans = _session.BeginTransaction())
            {
                try
                {
                    trans.Commit();
                }
                //catch (Exception StaleObjectStateException)
                catch (StaleObjectStateException se)
                {
                    trans.Rollback();
                    throw new ConcurrencyException("please reload the screen as changes have been made to entity since first viewing", se);
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }



        }
    }
}
